package controlador;

import helpers.IModelSerializer;
import helpers.IQueryFormer;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.ws.rs.core.MultivaluedMap;

import modelo.AbstractModel;

import persistencia.IDAOTEMPLATE;

import Common.InstancesPool;

public class SearchController extends AbstractController
{

	public SearchController()
	{
		
	}


	public String SearchForModelByURI(MultivaluedMap<String,String> SearchCriteria) throws IllegalArgumentException, IllegalAccessException
	{
		//Separamos para que quede el modelo en un string y el criterio de busqueda por otro lado
	    String Model = SearchCriteria.getFirst("model");
		String ParentModel = SearchCriteria.getFirst("ParentModel");
		String ParentChildAttribute = SearchCriteria.getFirst("ParentChildAttribute");
		String ParentModelID = SearchCriteria.getFirst("ParentModelID");
		int PageNumber = Integer.parseInt(SearchCriteria.getFirst("Page"));
		SearchCriteria.remove("model");
		SearchCriteria.remove("Page");
		SearchCriteria.remove("ParentModel");
		SearchCriteria.remove("ParentModelID");
		SearchCriteria.remove("ParentChildAttribute");
	    						
		
		IQueryFormer HQLformer = instancesPool.getHQLformer();
		
		
		String HQLQuery; 
		if(ParentModelID != null && ParentModel != null) //If we are looking for a child model
		{
			HQLQuery = HQLformer.formQuery(Model, ParentModel, ParentModelID, ParentChildAttribute, SearchCriteria);
		}
		else //If we aren't looking for a child model
		{
			HQLQuery = HQLformer.formQuery(Model, SearchCriteria);
		}
		
		IDAOTEMPLATE dao = instancesPool.getDao();
		
		List<AbstractModel> ObjectList = dao.searchObject(HQLQuery,PageNumber);
		
		IModelSerializer MS = instancesPool.getmSerializer();
		
		return MS.getXMLFromObjectList(ObjectList,10);
	
	}

	
	public String SearchForAnEmptyModel(String ModelName) throws Exception
	{
		String SerializedEmptyModel = instancesPool.getmSerializer().getXMLFromEmptyModel(ModelName);
		return SerializedEmptyModel;
	}
	
	
	public String SearchForAllModelNames()
	{
		String AllModelNames =  instancesPool.getDomainModelLister().returnAllDomainModelNames();
		return AllModelNames;
	}

}
